/* global Cesium */
import { EntityWrapper } from './EntityWrapper';
import { DescriptionHelper } from './DescriptionHelper';

export class GroundStationEntity extends EntityWrapper {
    constructor(viewer, sats, position, options) {
        super(viewer, options);
        this.sats = sats;
        this.image = options.image || '../../../Assets/images/marker.png';
        this.name = 'Ground station';
        this.position = position;

        this.createEntities();
    }

    // 创建实体对象
    createEntities() {
        this.createDescription();
        this.createGroundStation();
        let _self = this;
        this.viewer.selectedEntityChanged.addEventListener(() => {
            if (_self.isSelected) {
                _self.setSelectedOnTickCallback(clock => {
                    _self.sats.enabledSatellites.forEach(sat => {
                        sat.props.updatePasses(clock.currentTime);
                    });
                });
            }
        });
        // 设置默认的观测站
        // this.viewer.selectedEntity = this.defaultEntity;
    }
    // 创建观测站对象
    createGroundStation() {
        const billboard = new Cesium.BillboardGraphics({
            image: this.image,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            width: 24,
            height: 24,
        });
        this.createCesiumEntity(
            'Groundstation',
            'billboard',
            billboard,
            this.name,
            this.description,
            this.position.cartesian,
            false
        );
        this.defaultEntity = this.entities['Groundstation'];
    }
    // 创建属性信息
    createDescription() {
        let _self = this;
        const description = new Cesium.CallbackProperty(time => {
            const passes = _self.passes(time);
            const content = DescriptionHelper.renderDescription(
                time,
                _self.name,
                _self.position,
                passes,
                true
            );
            return content;
        }, false);
        this.description = description;
    }

    passes(time, deltaHours = 24) {
        let passes = [];
        // Aggregate passes from all enabled satellites
        this.sats.enabledSatellites.forEach(sat => {
            passes.push(...sat.props.passes);
        });

        // Filter passes based on time
        // passes = passes.filter((pass) => {
        //   return dayjs(pass.start).diff(time, "hours") < deltaHours;
        // });

        // Sort passes by time
        passes = passes.sort((a, b) => {
            return a.start - b.start;
        });
        return passes;
    }
}
